import cv2
import numpy as np

# 定义全局变量
drawing = False  # 是否正在绘制矩形
ix, iy = -1, -1  # 起始点坐标


# 鼠标事件回调函数
def draw_rectangle(event, x, y, flags, param):
    global ix, iy, drawing

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2)

        # 计算框内区域的灰度平均值
        roi = gray[iy:y, ix:x]
        mean_value = np.mean(roi)

        # 输出信息
        print(f"灰度平均值: {mean_value}")
        print(f"框内区域的行列信息: 行  列  {iy}, {y}, {ix}, {x}")


# 读取图像
# img = cv2.imread(r"E:\studylife\detectflaws\pythonCode\deepAndPhase\comsolCompareTrue\Hz(0.07)comsol .jpg")
img = cv2.imread(r"E:\infraVideos\20240530\1\Hz0.070000nodt1.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 创建窗口并将回调函数绑定到窗口
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_rectangle)

while True:
    cv2.imshow('image', img)

    # 通过按键 'ESC' 退出循环
    if cv2.waitKey(1) & 0xFF == 27:
        break

cv2.destroyAllWindows()
